package com.example.demo.webSocketDemo;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author qx
 * @date 2023/8/22
 * @des WebSocket处理类
 */
@Slf4j
@Component
public class SystemWebSocketHandler implements WebSocketHandler {
 
    // 存储所有客户端会话
    private static final List<WebSocketSession> sessionList = new ArrayList<>();
 
    /**
     * 与服务器连接成功
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("客户端成功建立连接:{}", session.getId());
        sessionList.add(session);
    }
 
    /**
     * 接受客户端的消息
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        // 获取客户端的消息
        String msg = message.getPayload().toString();
        log.info("接收到客户端的消息:{}", msg);
        sendMsg(msg);
    }
 
    /**
     * 给所有客户端发送消息
     *
     * @param msg 消息内容
     * @throws IOException
     */
    private void sendMsg(String msg) throws IOException {
        for (WebSocketSession session : sessionList) {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(msg));
            }
        }
    }
 
    /**
     * 通讯异常
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("通讯出现异常");
    }
 
    /**
     * 连接关闭
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("连接关闭");
    }
 
    /**
     * 是否允许分段发送
     */
    @Override
    public boolean supportsPartialMessages() {
        // 一次性发送消息
        return false;
    }
}